/**
 * 封装axios
 */

import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth'

// 错误信息处理函数
const errorHandle = (status, other) => {
  switch (status) {
    case 400:
      // 请求次数的限制
      console.log('服务器请求限制', status, other.data)
      alert(other.data)
      break
    case 401:
      console.log('用户信息验证失败')
      break
    case 403:
      console.log('请求被限制')
      break
    case 404:
      console.log('客户端错误')
      break
    case -401:
      removeToken()
      router.push('/login')
      console.log('token过期 请重新登录')
      break
    default:
      console.log(other)
      break
  }
}

const instance = axios.create({
  timeout: 5000
})

/**
 * token:登陆 令牌
 */

instance.defaults.baseURL = ''
instance.defaults.headers.post['Content-Type'] = 'application/json'
instance.defaults.headers.put['Content-Type'] = 'application/json'

// 拦截器
// 添加请求拦截器
instance.interceptors.request.use(config => {
  if (config.method === 'post' || config.method === 'put') {
    config.data = JSON.stringify(config.data)
  }
  console.log(66666)
  if (store.state.token) {
    console.log('自定义token')
    // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['Authorization'] = getToken()
  }
  return config
}, error => Promise.reject(error))

// 添加响应拦截器
instance.interceptors.response.use(
  // 成功
  response => {
    // 刷新Token
    let accessToken = response.headers['authorization']
    if (accessToken) {
      console.log('RefreshToken:' + accessToken)
      removeToken()
      setToken(accessToken)
    }
    console.log(response)
    if (response.data.code === 200) {
      console.log(6666)
      return Promise.resolve(response)
    } else if (response.data.code === -401) {
      removeToken()
      router.push('/login')
      return Promise.reject(response)
    }
  },
  // 失败
  error => {
    const {response} = error
    if (response) {
      errorHandle(response.status, response.data)
      return Promise.reject(response)
    } else {
      // response不存在，服务器没有响应
      console.log('请求被中断')
    }
  }
)
// 导出
export default instance
